﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DotNetNuke;
using DotNetNuke.Entities.Users;
using DotNetNuke.Professional.Commerce;
using DotNetNuke.Professional.Commerce.Orders;
using DotNetNuke.Professional.Commerce.Data;


namespace CommerceSamples {
    /// <summary>
    /// Custom Action value that you enter for
    /// the product for this action is:
    /// CommerceSamples.ProfileCounterAction, CommerceSamples
    /// NOTE: Make sure you copy the CommerceSamples.dll file to your bin directory.
    /// </summary>
    public class ProfileCounterAction : IOrderAction {
        /// <summary>
        /// Since an order can contain multiple 
        /// products we want to make sure we limit to the product for this action
        /// </summary>
        const string ActionSku = "COUNT123";

        public void ProcessOrderAction(int ModuleId, int PortalId, Guid OrderId) {

            //Example of how we would get the OrderInfo object
            OrdersController orders = new OrdersController();
            OrderInfo order = orders.Order_Get(ModuleId, PortalId, OrderId);

            //Example of how we would get the UserInfo of the person placing the order;
            DotNetNuke.Entities.Users.UserController users = new DotNetNuke.Entities.Users.UserController();
            UserInfo user = users.GetUser(PortalId, order.UserId);
            //Get the current value from the profile property
            //MAKE SURE YOU HAVE CREATED THE PROPERTY CALLED COUNTER!
            int counter = int.Parse(user.Profile.GetPropertyValue("Counter"));
            if (counter < 0) {
                counter = 0;
            }

            //Update a profile property
            foreach (OrderDetailsInfo orderItem in order.OrderDetails) {
                if (orderItem.ProductSKU == ActionSku) {
                    //We want to add 10 for every item that was purchased
                    counter = (orderItem.Qty * 10) + counter;
                }
            }
            user.Profile.SetProfileProperty("Counter", counter.ToString());
            DotNetNuke.Entities.Users.UserController.UpdateUser(PortalId, user);

            //We want to add a order log message with our results
            DataProvider.Instance().OrderLog_Save(OrderId, Guid.Empty, ActionTypes.ProcessCustomAction.ToString(), 1, "Increased Counter to " + counter.ToString());

        }
        /// <summary>
        /// This is only a placeholder at this time.  This method is not currently implemented.
        /// </summary>
        /// <param name="ModuleId"></param>
        /// <param name="PortalId"></param>
        /// <param name="OrderId"></param>
        public void ReverseOrderAction(int ModuleId, int PortalId, Guid OrderId) {

        }
    }
}
